<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/18
 * Time: 22:00
 */

namespace App\Admin\Controllers;

use App\Admin\Actions\RobotLoginRenderable;
use App\Admin\Actions\WakeUpAction;
use App\Admin\Actions\WakeUpRenderable;
use App\Admin\Traits\UserTrait;
use App\Helper;
use App\Lib\Sdk\Manager;
use App\Lib\Sdk\Robot\Service\Robot;
use App\Models\Robots;
use App\Models\Send;
use App\User;
use Encore\Admin\Actions\Action;
use Encore\Admin\Admin;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;

class RobotsController extends AdminController
{
    use UserTrait;


    public function index(Content $content)
    {
        $grid = $this->grid();
        return $content
            ->title("机器人列表")
            ->body($grid);
    }


    public function grid()
    {
        $model = new Robots();
        $grid = new Grid($model);
        if (!$this->isAdministrator()) {
            $grid->model()->where('user_id', $this->getUserId());
        }

        $grid->disableCreateButton();
        $grid->disableExport();
        Helper::gridLoadModel($grid, $model);
        $grid->column("代理手机号")->display(function() {
            $user = \App\Models\User::where("id",  $this->user_id)->first();
            return $user->mobile;
        });
        $grid->column("登录状态")->display(function()  {
            $manager = Manager::getSdk();
            $status = $manager->heartBeat($this);
            if ($status) {
                return "<label class='label label-success'>在线</label>";
            } else {
                if (!$status) {
                    admin_toastr($manager->getErrorMessage(), 'warning');
                }
                return "<label class='label label-danger'>离线</label>";
            }
        });

        if (!$this->isAdministrator()) {
            if(empty($this->wxid)){
                $grid->column("二维码登录")->modal("请使用微信扫描二维码", RobotLoginRenderable::class);
            }else{
                $grid->column("唤醒")->modal("唤醒", WakeUpRenderable::class);
            }
        }

        $grid->disableActions();
        return $grid;
    }

    public function checklogin(Request $request)
    {
        $uid = $request->get("uid");
        $robot = Robots::where("user_id", $uid)->first();
        $res = !empty($robot->wxid);
        $manager = Manager::getSdk();
        if (!$res) {
            $manager->checkLogin($robot);
        }
        return \GuzzleHttp\json_encode(['status' => (int)$res, 'message' => $manager->getErrorMessage()]);
    }
}